﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using SharpChess;
using MooneyTool;

namespace TwitterChess
{
	class GameWrapper
	{
		//private Game game;
		private Player ai;
		private TwitterOpponent opponent;
		private bool isHumanTurn;
		private GameManager manager;

		public TwitterOpponent Opponent
		{
			get
			{
				return opponent;
			}
		}

		public GameWrapper(TwitterOpponent opponent, GameManager manager)
		{
			this.manager = manager;

			Game.PlayerBlack.Intellegence = Player.enmIntellegence.Human;
			Game.PlayerWhite.Intellegence = Player.enmIntellegence.Computer;

			this.opponent = opponent;
			this.opponent.player = Game.PlayerBlack;

			this.ai = Game.PlayerWhite;
			this.ai.ReadyToMakeMove += new Player.delegatetypePlayerEvent(DoAiMove);
			this.Load();
			//this.game = new Game();
			Game.New();
			this.ai.StartThinking();
			this.isHumanTurn = false;
		}

		private void DoAiMove()
		{
			Move move = null;
			if (Game.PlayerToPlay.PrincipalVariation.Count > 0)
			{
				move = Game.PlayerToPlay.PrincipalVariation[0];
			}
			else
			{
				throw new ApplicationException("Player_ReadToMakeMove: Principal Variation is empty.");
			}
			
			//manager.OnAIMoveMade(this, new AIMoveMadeArgs(move.DebugText, opponent));

			string moveText = move.ToPgn();
			manager.OnAIMoveMade(this, new AIMoveMadeArgs(moveText, opponent));

			Game.MakeAMove(move.Name, move.Piece, move.To);

			isHumanTurn = true;
		}

		public void DoPlayerMove(Move move)
		{
			while (!isHumanTurn)
			{
				Thread.Sleep(100);
			}
			Game.MakeAMove(move.Name, move.Piece, move.To);
			isHumanTurn = false;
			this.ai.StartThinking();
		}

		public void DoNothing()
		{

		}

		private void Load()
		{
			Game.PlayerWhite.MoveConsidered += new Player.delegatetypePlayerEvent(DoNothing);
			Game.PlayerBlack.MoveConsidered += new Player.delegatetypePlayerEvent(DoNothing);
			Game.PlayerWhite.ThinkingBeginning += new Player.delegatetypePlayerEvent(DoNothing);
			Game.PlayerBlack.ThinkingBeginning += new Player.delegatetypePlayerEvent(DoNothing);

			Game.BoardPositionChanged += new Game.delegatetypeGameEvent(DoNothing);
			Game.GamePaused += new Game.delegatetypeGameEvent(DoNothing);
			Game.GameResumed += new Game.delegatetypeGameEvent(DoNothing);
			Game.GameSaved += new Game.delegatetypeGameEvent(DoNothing);
			Game.SettingsUpdated += new Game.delegatetypeGameEvent(DoNothing);

			//Game.BackupGamePath = Application.StartupPath + @"\BackupGame.sharpchess";
		}
	}
}
